package com.study.springboot.config;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author xuxw
 * @time 2019年9月2日下午1:48:17
 * @desc
 */
@Configuration
public class RabbitMQConfig {
	
	@Value("${rabbitmq.host}")
    private String rabbitHost;

    @Value("${rabbitmq.username}")
    private String rabbitUserName;

    @Value("${rabbitmq.password}")
    private String rabbitPassword;

    @Value("${rabbitmq.port}")
    private Integer rabbitPort;

	@Bean
	public ConnectionFactory connectionFactory(){
		CachingConnectionFactory connFactory = new CachingConnectionFactory();
		connFactory.setAddresses(rabbitHost);
        connFactory.setUsername(rabbitUserName);
        connFactory.setPassword(rabbitPassword);
        connFactory.setPort(rabbitPort);
        connFactory.setPublisherConfirms(true);
		return connFactory;
	}
	
	@Bean
    public MessageConverter jsonMessageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    
    @Bean
    public RabbitTemplate rabbitTemplate()
    {
        ConnectionFactory factory = connectionFactory();
        RabbitTemplate template = new RabbitTemplate(factory);
        template.setMessageConverter(jsonMessageConverter());
        return template;
    }
}
